package com.woniuxy.cq.phrase3.component;

import com.woniuxy.cq.phrase3.dao.UserMapper;
import com.woniuxy.cq.phrase3.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.Set;


/**
 * @Author Daniel
 * @Description Realm类
 * @Date 17:57 2020/9/2
 * @Param
 * @return
 **/
@Slf4j
public class ShiroRealm extends AuthorizingRealm {

    @Resource
    private UserMapper userMapper;

    /**
     * 授权信息
     * @param principal
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        //1.取出登陆成功的对象
        User user = (User)principal.getPrimaryPrincipal();
        //2.加载用户的角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //3.查询数据库获取角色列表 并设置进去
        Set<String> rolesSet = userMapper.findRolesById(user.getUserId());
        log.info("角色{}",rolesSet);
        System.out.println("角色:"+rolesSet);
        simpleAuthorizationInfo.setRoles(rolesSet);
        //4.查询数据库获取权限列表 并设置进去
        Set<String> permissions = userMapper.findPermsById(user.getUserId());
        log.info("权限{}",permissions);
        System.out.println("权限:"+permissions);
        simpleAuthorizationInfo.setStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    /**
     * 二.认证方法 doGetAuthenticationInfo
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        User user = userMapper.findByName((String) token.getPrincipal());
        log.info("登录后返回的数据{}",user);
        //1.判断验证结果
        if(user == null){throw new UnknownAccountException("账户不存在");}
        //2.返回
        return new SimpleAuthenticationInfo(user,user.getUserPass(), ByteSource.Util.bytes(user.getUserSalt()),getName());
    }
}
